<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>TS入门 | Jushden的个人博客</title><meta name="author" content="Jushden"><meta name="copyright" content="Jushden"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="第一章 快速入门0、TypeScript简介 TypeScript是JavaScript的超集。 它对JS进行了扩展，向JS中引入了类型的概念，并添加了许多新的特性。 TS代码需要通过编译器编译为JS，然后再交由JS解析器执行。 TS完全兼容JS，换言之，任何的JS代码都可以直接当成JS使用。 相较于JS而言，TS拥有了静态类型，更加严格的语法，更强大的功能；TS可以在代码执行前就完成代码的检查，">
<meta property="og:type" content="article">
<meta property="og:title" content="TS入门">
<meta property="og:url" content="https://jushden.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/index.html">
<meta property="og:site_name" content="Jushden的个人博客">
<meta property="og:description" content="第一章 快速入门0、TypeScript简介 TypeScript是JavaScript的超集。 它对JS进行了扩展，向JS中引入了类型的概念，并添加了许多新的特性。 TS代码需要通过编译器编译为JS，然后再交由JS解析器执行。 TS完全兼容JS，换言之，任何的JS代码都可以直接当成JS使用。 相较于JS而言，TS拥有了静态类型，更加严格的语法，更强大的功能；TS可以在代码执行前就完成代码的检查，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img1.baidu.com/it/u=3255567619,1492410640&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500">
<meta property="article:published_time" content="2023-07-29T09:15:15.878Z">
<meta property="article:modified_time" content="2023-07-29T09:19:07.984Z">
<meta property="article:author" content="Jushden">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img1.baidu.com/it/u=3255567619,1492410640&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"><link rel="shortcut icon" href="/zhuxiaodong.gitee.io/img/favicon.png"><link rel="canonical" href="https://jushden.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/zhuxiaodong.gitee.io/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/zhuxiaodong.gitee.io/',
  algolia: undefined,
  localSearch: {"path":"/zhuxiaodong.gitee.io/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'TS入门',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-29 17:19:07'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/zhuxiaodong.gitee.io/img/duola.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/zhuxiaodong.gitee.io/archives/"><div class="headline">文章</div><div class="length-num">12</div></a><a href="/zhuxiaodong.gitee.io/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/zhuxiaodong.gitee.io/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zhuxiaodong.gitee.io/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zhuxiaodong.gitee.io/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500')"><nav id="nav"><span id="blog-info"><a href="/zhuxiaodong.gitee.io/" title="Jushden的个人博客"><span class="site-name">Jushden的个人博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zhuxiaodong.gitee.io/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zhuxiaodong.gitee.io/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/zhuxiaodong.gitee.io/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/zhuxiaodong.gitee.io/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">TS入门</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-29T09:15:15.878Z" title="发表于 2023-07-29 17:15:15">2023-07-29</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-29T09:19:07.984Z" title="更新于 2023-07-29 17:19:07">2023-07-29</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="TS入门"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第一章-快速入门"><a href="#第一章-快速入门" class="headerlink" title="第一章 快速入门"></a>第一章 快速入门</h1><h2 id="0、TypeScript简介"><a href="#0、TypeScript简介" class="headerlink" title="0、TypeScript简介"></a>0、TypeScript简介</h2><ol>
<li>TypeScript是JavaScript的超集。</li>
<li>它对JS进行了扩展，向JS中引入了类型的概念，并添加了许多新的特性。</li>
<li>TS代码需要通过编译器编译为JS，然后再交由JS解析器执行。</li>
<li>TS完全兼容JS，换言之，任何的JS代码都可以直接当成JS使用。</li>
<li>相较于JS而言，TS拥有了静态类型，更加严格的语法，更强大的功能；TS可以在代码执行前就完成代码的检查，减小了运行时异常的出现的几率；TS代码可以编译为任意版本的JS代码，可有效解决不同JS运行环境的兼容问题；同样的功能，TS的代码量要大于JS，但由于TS的代码结构更加清晰，变量类型更加明确，在后期代码的维护中TS却远远胜于JS。</li>
</ol>
<h2 id="1、TypeScript-开发环境搭建"><a href="#1、TypeScript-开发环境搭建" class="headerlink" title="1、TypeScript 开发环境搭建"></a>1、TypeScript 开发环境搭建</h2><ol>
<li><p>下载Node.js</p>
<ul>
<li>64位：<a target="_blank" rel="noopener" href="https://nodejs.org/dist/v14.15.1/node-v14.15.1-x64.msi">https://nodejs.org/dist/v14.15.1/node-v14.15.1-x64.msi</a></li>
<li>32位：<a target="_blank" rel="noopener" href="https://nodejs.org/dist/v14.15.1/node-v14.15.1-x86.msi">https://nodejs.org/dist/v14.15.1/node-v14.15.1-x86.msi</a></li>
</ul>
</li>
<li><p>安装Node.js</p>
</li>
<li><p>使用npm全局安装typescript</p>
<ul>
<li>进入命令行</li>
<li>输入：npm i -g typescript</li>
</ul>
</li>
<li><p>创建一个ts文件</p>
</li>
<li><p>使用tsc对ts文件进行编译</p>
<ul>
<li><p>进入命令行</p>
</li>
<li><p>进入ts文件所在目录</p>
</li>
<li><p>执行命令：tsc xxx.ts</p>
</li>
</ul>
</li>
</ol>
<h2 id="2、基本类型"><a href="#2、基本类型" class="headerlink" title="2、基本类型"></a>2、基本类型</h2><ul>
<li><p>类型声明</p>
<ul>
<li><p>类型声明是TS非常重要的一个特点</p>
</li>
<li><p>通过类型声明可以指定TS中变量（参数、形参）的类型</p>
</li>
<li><p>指定类型后，当为变量赋值时，TS编译器会自动检查值是否符合类型声明，符合则赋值，否则报错</p>
</li>
<li><p>简而言之，类型声明给变量设置了类型，使得变量只能存储某种类型的值</p>
</li>
<li><p>语法：</p>
<ul>
<li><pre><code class="typescript">let 变量: 类型;

let 变量: 类型 = 值;

function fn(参数: 类型, 参数: 类型): 类型&#123;
    ...
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- 自动类型判断</span><br><span class="line"></span><br><span class="line">  - TS拥有自动的类型判断机制</span><br><span class="line">  - 当对变量的声明和赋值是同时进行的，TS编译器会自动判断变量的类型</span><br><span class="line">  - 所以如果你的变量的声明和赋值时同时进行的，可以省略掉类型声明</span><br><span class="line"></span><br><span class="line">- 类型：</span><br><span class="line"></span><br><span class="line">  |  类型   |       例子        |              描述              |</span><br><span class="line">  | :-----: | :---------------: | :----------------------------: |</span><br><span class="line">  | number  |    1, -33, 2.5    |            任意数字            |</span><br><span class="line">  | string  | &#x27;hi&#x27;, &quot;hi&quot;, `hi`  |           任意字符串           |</span><br><span class="line">  | boolean |    true、false    |       布尔值true或false        |</span><br><span class="line">  | 字面量  |      其本身       |  限制变量的值就是该字面量的值  |</span><br><span class="line">  |   any   |         *         |            任意类型            |</span><br><span class="line">  | unknown |         *         |         类型安全的any          |</span><br><span class="line">  |  void   | 空值（undefined） |     没有值（或undefined）      |</span><br><span class="line">  |  never  |      没有值       |          不能是任何值          |</span><br><span class="line">  | object  |  &#123;name:&#x27;孙悟空&#x27;&#125;  |          任意的JS对象          |</span><br><span class="line">  |  array  |      [1,2,3]      |           任意JS数组           |</span><br><span class="line">  |  tuple  |       [4,5]       | 元素，TS新增类型，固定长度数组 |</span><br><span class="line">  |  enum   |    enum&#123;A, B&#125;     |       枚举，TS中新增类型       |</span><br><span class="line"></span><br><span class="line">- number</span><br><span class="line"></span><br><span class="line">  - ```typescript</span><br><span class="line">    let decimal: number = 6;</span><br><span class="line">    let hex: number = 0xf00d;</span><br><span class="line">    let binary: number = 0b1010;</span><br><span class="line">    let octal: number = 0o744;</span><br><span class="line">    let big: bigint = 100n;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
<li><p>boolean</p>
<ul>
<li><pre><code class="typescript">let isDone: boolean = false;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- string</span><br><span class="line"></span><br><span class="line">  - ```typescript</span><br><span class="line">    let color: string = &quot;blue&quot;;</span><br><span class="line">    color = &#x27;red&#x27;;</span><br><span class="line">    </span><br><span class="line">    let fullName: string = `Bob Bobbington`;</span><br><span class="line">    let age: number = 37;</span><br><span class="line">    let sentence: string = `Hello, my name is $&#123;fullName&#125;.</span><br><span class="line">    </span><br><span class="line">    I&#x27;ll be $&#123;age + 1&#125; years old next month.`;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>字面量</p>
<ul>
<li><p>也可以使用字面量去指定变量的类型，通过字面量可以确定变量的取值范围</p>
</li>
<li><pre><code class="typescript">let color: &#39;red&#39; | &#39;blue&#39; | &#39;black&#39;;
let num: 1 | 2 | 3 | 4 | 5;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- any</span><br><span class="line"></span><br><span class="line">  - ```typescript</span><br><span class="line">    let d: any = 4;</span><br><span class="line">    d = &#x27;hello&#x27;;</span><br><span class="line">    d = true;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>unknown</p>
<ul>
<li><pre><code class="typescript">let notSure: unknown = 4;
notSure = &#39;hello&#39;;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- void</span><br><span class="line"></span><br><span class="line">  - ```typescript</span><br><span class="line">    let unusable: void = undefined;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>never</p>
<ul>
<li><pre><code class="typescript">function error(message: string): never &#123;
  throw new Error(message);
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- object（没啥用）</span><br><span class="line"></span><br><span class="line">  - ```typescript</span><br><span class="line">    let obj: object = &#123;&#125;;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>array</p>
<ul>
<li><pre><code class="typescript">let list: number[] = [1, 2, 3];
let list: Array&lt;number&gt; = [1, 2, 3];
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- tuple</span><br><span class="line"></span><br><span class="line">  - ```typescript</span><br><span class="line">    let x: [string, number];</span><br><span class="line">    x = [&quot;hello&quot;, 10]; </span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>enum</p>
<ul>
<li><pre><code class="typescript">enum Color &#123;
  Red,
  Green,
  Blue,
&#125;
let c: Color = Color.Green;

enum Color &#123;
  Red = 1,
  Green,
  Blue,
&#125;
let c: Color = Color.Green;

enum Color &#123;
  Red = 1,
  Green = 2,
  Blue = 4,
&#125;
let c: Color = Color.Green;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- 类型断言</span><br><span class="line"></span><br><span class="line">  - 有些情况下，变量的类型对于我们来说是很明确，但是TS编译器却并不清楚，此时，可以通过类型断言来告诉编译器变量的类型，断言有两种形式：</span><br><span class="line"></span><br><span class="line">    - 第一种</span><br><span class="line"></span><br><span class="line">      - ```typescript</span><br><span class="line">        let someValue: unknown = &quot;this is a string&quot;;</span><br><span class="line">        let strLength: number = (someValue as string).length;</span><br></pre></td></tr></table></figure>

- 第二种

  - ```typescript
    let someValue: unknown = &quot;this is a string&quot;;
    let strLength: number = (&lt;string&gt;someValue).length;
    <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">## 3、编译选项</span><br><span class="line"></span><br><span class="line">- 自动编译文件</span><br><span class="line"></span><br><span class="line">  - 编译文件时，使用 -w 指令后，TS编译器会自动监视文件的变化，并在文件发生变化时对文件进行重新编译。</span><br><span class="line"></span><br><span class="line">  - 示例：</span><br><span class="line"></span><br><span class="line">    - ```powershell</span><br><span class="line">      tsc xxx.ts -w</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>自动编译整个项目</p>
<ul>
<li><p>如果直接使用tsc指令，则可以自动将当前项目下的所有ts文件编译为js文件。</p>
</li>
<li><p>但是能直接使用tsc命令的前提时，要先在项目根目录下创建一个ts的配置文件 tsconfig.json</p>
</li>
<li><p>tsconfig.json是一个JSON文件，添加配置文件后，只需只需 tsc 命令即可完成对整个项目的编译</p>
</li>
<li><p>配置选项：</p>
<ul>
<li><p>include</p>
<ul>
<li><p>定义希望被编译文件所在的目录</p>
</li>
<li><p>默认值：[“**&#x2F;*“]</p>
</li>
<li><p>示例：</p>
<ul>
<li><pre><code class="json">&quot;include&quot;:[&quot;src/**/*&quot;, &quot;tests/**/*&quot;]
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    - 上述示例中，所有src目录和tests目录下的文件都会被编译</span><br><span class="line"></span><br><span class="line">- exclude</span><br><span class="line"></span><br><span class="line">  - 定义需要排除在外的目录</span><br><span class="line"></span><br><span class="line">  - 默认值：[&quot;node_modules&quot;, &quot;bower_components&quot;, &quot;jspm_packages&quot;]</span><br><span class="line"></span><br><span class="line">  - 示例：</span><br><span class="line"></span><br><span class="line">    - ```json</span><br><span class="line">      &quot;exclude&quot;: [&quot;./src/hello/**/*&quot;]</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
<li><p>上述示例中，src下hello目录下的文件都不会被编译</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>extends</p>
<ul>
<li><p>定义被继承的配置文件</p>
</li>
<li><p>示例：</p>
<ul>
<li><pre><code class="json">&quot;extends&quot;: &quot;./configs/base&quot;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    - 上述示例中，当前配置文件中会自动包含config目录下base.json中的所有配置信息</span><br><span class="line"></span><br><span class="line">- files</span><br><span class="line"></span><br><span class="line">  - 指定被编译文件的列表，只有需要编译的文件少时才会用到</span><br><span class="line"></span><br><span class="line">  - 示例：</span><br><span class="line"></span><br><span class="line">    - ```json</span><br><span class="line">      &quot;files&quot;: [</span><br><span class="line">          &quot;core.ts&quot;,</span><br><span class="line">          &quot;sys.ts&quot;,</span><br><span class="line">          &quot;types.ts&quot;,</span><br><span class="line">          &quot;scanner.ts&quot;,</span><br><span class="line">          &quot;parser.ts&quot;,</span><br><span class="line">          &quot;utilities.ts&quot;,</span><br><span class="line">          &quot;binder.ts&quot;,</span><br><span class="line">          &quot;checker.ts&quot;,</span><br><span class="line">          &quot;tsc.ts&quot;</span><br><span class="line">        ]</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
<li><p>列表中的文件都会被TS编译器所编译</p>
</li>
</ul>
</li>
<li><p>compilerOptions</p>
<ul>
<li><p>编译选项是配置文件中非常重要也比较复杂的配置选项</p>
</li>
<li><p>在compilerOptions中包含多个子选项，用来完成对编译的配置</p>
<ul>
<li><p>项目选项</p>
<ul>
<li><p>target</p>
<ul>
<li><p>设置ts代码编译的目标版本</p>
</li>
<li><p>可选值：</p>
<ul>
<li>ES3（默认）、ES5、ES6&#x2F;ES2015、ES7&#x2F;ES2016、ES2017、ES2018、ES2019、ES2020、ESNext</li>
</ul>
</li>
<li><p>示例：</p>
<ul>
<li><pre><code class="json">&quot;compilerOptions&quot;: &#123;
    &quot;target&quot;: &quot;ES6&quot;
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    - 如上设置，我们所编写的ts代码将会被编译为ES6版本的js代码</span><br><span class="line"></span><br><span class="line">- lib</span><br><span class="line"></span><br><span class="line">  - 指定代码运行时所包含的库（宿主环境）</span><br><span class="line"></span><br><span class="line">  - 可选值：</span><br><span class="line"></span><br><span class="line">    - ES5、ES6/ES2015、ES7/ES2016、ES2017、ES2018、ES2019、ES2020、ESNext、DOM、WebWorker、ScriptHost ......</span><br><span class="line"></span><br><span class="line">  - 示例：</span><br><span class="line"></span><br><span class="line">    - ```json</span><br><span class="line">      &quot;compilerOptions&quot;: &#123;</span><br><span class="line">          &quot;target&quot;: &quot;ES6&quot;,</span><br><span class="line">          &quot;lib&quot;: [&quot;ES6&quot;, &quot;DOM&quot;],</span><br><span class="line">          &quot;outDir&quot;: &quot;dist&quot;,</span><br><span class="line">          &quot;outFile&quot;: &quot;dist/aa.js&quot;</span><br><span class="line">      &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
<li><p>module</p>
<ul>
<li><p>设置编译后代码使用的模块化系统</p>
</li>
<li><p>可选值：</p>
<ul>
<li>CommonJS、UMD、AMD、System、ES2020、ESNext、None</li>
</ul>
</li>
<li><p>示例：</p>
<ul>
<li><pre><code class="typescript">&quot;compilerOptions&quot;: &#123;
    &quot;module&quot;: &quot;CommonJS&quot;
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- outDir</span><br><span class="line"></span><br><span class="line">  - 编译后文件的所在目录</span><br><span class="line"></span><br><span class="line">  - 默认情况下，编译后的js文件会和ts文件位于相同的目录，设置outDir后可以改变编译后文件的位置</span><br><span class="line"></span><br><span class="line">  - 示例：</span><br><span class="line"></span><br><span class="line">    - ```json</span><br><span class="line">      &quot;compilerOptions&quot;: &#123;</span><br><span class="line">          &quot;outDir&quot;: &quot;dist&quot;</span><br><span class="line">      &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
<li><p>设置后编译后的js文件将会生成到dist目录</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>outFile</p>
<ul>
<li><p>将所有的文件编译为一个js文件</p>
</li>
<li><p>默认会将所有的编写在全局作用域中的代码合并为一个js文件，如果module制定了None、System或AMD则会将模块一起合并到文件之中</p>
</li>
<li><p>示例：</p>
<ul>
<li><pre><code class="json">&quot;compilerOptions&quot;: &#123;
    &quot;outFile&quot;: &quot;dist/app.js&quot;
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- rootDir</span><br><span class="line"></span><br><span class="line">  - 指定代码的根目录，默认情况下编译后文件的目录结构会以最长的公共目录为根目录，通过rootDir可以手动指定根目录</span><br><span class="line"></span><br><span class="line">  - 示例：</span><br><span class="line"></span><br><span class="line">    - ```json</span><br><span class="line">      &quot;compilerOptions&quot;: &#123;</span><br><span class="line">          &quot;rootDir&quot;: &quot;./src&quot;</span><br><span class="line">      &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
<li><p>allowJs</p>
<ul>
<li>是否对js文件编译</li>
</ul>
</li>
<li><p>checkJs</p>
<ul>
<li><p>是否对js文件进行检查</p>
</li>
<li><p>示例：</p>
<ul>
<li><pre><code class="json">&quot;compilerOptions&quot;: &#123;
    &quot;allowJs&quot;: true,
    &quot;checkJs&quot;: true
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">            - removeComments</span><br><span class="line"></span><br><span class="line">              - 是否删除注释</span><br><span class="line">              - 默认值：false</span><br><span class="line"></span><br><span class="line">            - noEmit</span><br><span class="line"></span><br><span class="line">              - 不对代码进行编译</span><br><span class="line">              - 默认值：false</span><br><span class="line"></span><br><span class="line">            - sourceMap</span><br><span class="line"></span><br><span class="line">              - 是否生成sourceMap</span><br><span class="line">              - 默认值：false</span><br><span class="line"></span><br><span class="line">              </span><br><span class="line"></span><br><span class="line">          - 严格检查</span><br><span class="line"></span><br><span class="line">            - strict</span><br><span class="line">              - 启用所有的严格检查，默认值为true，设置后相当于开启了所有的严格检查</span><br><span class="line">            - alwaysStrict</span><br><span class="line">              - 总是以严格模式对代码进行编译</span><br><span class="line">            - noImplicitAny</span><br><span class="line">              - 禁止隐式的any类型</span><br><span class="line">            - noImplicitThis</span><br><span class="line">              - 禁止类型不明确的this</span><br><span class="line">            - strictBindCallApply</span><br><span class="line">              - 严格检查bind、call和apply的参数列表</span><br><span class="line">            - strictFunctionTypes</span><br><span class="line">              - 严格检查函数的类型</span><br><span class="line">            - strictNullChecks</span><br><span class="line">              - 严格的空值检查</span><br><span class="line">            - strictPropertyInitialization</span><br><span class="line">              - 严格检查属性是否初始化</span><br><span class="line"></span><br><span class="line">          - 额外检查</span><br><span class="line"></span><br><span class="line">            - noFallthroughCasesInSwitch</span><br><span class="line">              - 检查switch语句包含正确的break</span><br><span class="line">            - noImplicitReturns</span><br><span class="line">              - 检查函数没有隐式的返回值</span><br><span class="line">            - noUnusedLocals</span><br><span class="line">              - 检查未使用的局部变量</span><br><span class="line">            - noUnusedParameters</span><br><span class="line">              - 检查未使用的参数</span><br><span class="line"></span><br><span class="line">          - 高级</span><br><span class="line"></span><br><span class="line">            - allowUnreachableCode</span><br><span class="line">              - 检查不可达代码</span><br><span class="line">              - 可选值：</span><br><span class="line">                - true，忽略不可达代码</span><br><span class="line">                - false，不可达代码将引起错误</span><br><span class="line">            - noEmitOnError</span><br><span class="line">              - 有错误的情况下不进行编译</span><br><span class="line">              - 默认值：false</span><br><span class="line"></span><br><span class="line">## 4、webpack</span><br><span class="line"></span><br><span class="line">- 通常情况下，实际开发中我们都需要使用构建工具对代码进行打包，TS同样也可以结合构建工具一起使用，下边以webpack为例介绍一下如何结合构建工具使用TS。</span><br><span class="line"></span><br><span class="line">- 步骤：</span><br><span class="line"></span><br><span class="line">  1. 初始化项目</span><br><span class="line"></span><br><span class="line">     - 进入项目根目录，执行命令 ``` npm init -y```</span><br><span class="line">       - 主要作用：创建package.json文件</span><br><span class="line"></span><br><span class="line">  2. 下载构建工具</span><br><span class="line"></span><br><span class="line">     - ```npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin```</span><br><span class="line">       - 共安装了7个包</span><br><span class="line">         - webpack</span><br><span class="line">           - 构建工具webpack</span><br><span class="line">         - webpack-cli</span><br><span class="line">           - webpack的命令行工具</span><br><span class="line">         - webpack-dev-server</span><br><span class="line">           - webpack的开发服务器</span><br><span class="line">         - typescript</span><br><span class="line">           - ts编译器</span><br><span class="line">         - ts-loader</span><br><span class="line">           - ts加载器，用于在webpack中编译ts文件</span><br><span class="line">         - html-webpack-plugin</span><br><span class="line">           - webpack中html插件，用来自动创建html文件</span><br><span class="line">         - clean-webpack-plugin</span><br><span class="line">           - webpack中的清除插件，每次构建都会先清除目录</span><br><span class="line"></span><br><span class="line">  3. 根目录下创建webpack的配置文件webpack.config.js</span><br><span class="line"></span><br><span class="line">     - ```javascript</span><br><span class="line">       const path = require(&quot;path&quot;);</span><br><span class="line">       const HtmlWebpackPlugin = require(&quot;html-webpack-plugin&quot;);</span><br><span class="line">       const &#123; CleanWebpackPlugin &#125; = require(&quot;clean-webpack-plugin&quot;);</span><br><span class="line">       </span><br><span class="line">       module.exports = &#123;</span><br><span class="line">           optimization:&#123;</span><br><span class="line">               minimize: false // 关闭代码压缩，可选</span><br><span class="line">           &#125;,</span><br><span class="line">       </span><br><span class="line">           entry: &quot;./src/index.ts&quot;,</span><br><span class="line">           </span><br><span class="line">           devtool: &quot;inline-source-map&quot;,</span><br><span class="line">           </span><br><span class="line">           devServer: &#123;</span><br><span class="line">               contentBase: &#x27;./dist&#x27;</span><br><span class="line">           &#125;,</span><br><span class="line">       </span><br><span class="line">           output: &#123;</span><br><span class="line">               path: path.resolve(__dirname, &quot;dist&quot;),</span><br><span class="line">               filename: &quot;bundle.js&quot;,</span><br><span class="line">               environment: &#123;</span><br><span class="line">                   arrowFunction: false // 关闭webpack的箭头函数，可选</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;,</span><br><span class="line">       </span><br><span class="line">           resolve: &#123;</span><br><span class="line">               extensions: [&quot;.ts&quot;, &quot;.js&quot;]</span><br><span class="line">           &#125;,</span><br><span class="line">           </span><br><span class="line">           module: &#123;</span><br><span class="line">               rules: [</span><br><span class="line">                   &#123;</span><br><span class="line">                       test: /\.ts$/,</span><br><span class="line">                       use: &#123;</span><br><span class="line">                          loader: &quot;ts-loader&quot;     </span><br><span class="line">                       &#125;,</span><br><span class="line">                       exclude: /node_modules/</span><br><span class="line">                   &#125;</span><br><span class="line">               ]</span><br><span class="line">           &#125;,</span><br><span class="line">       </span><br><span class="line">           plugins: [</span><br><span class="line">               new CleanWebpackPlugin(),</span><br><span class="line">               new HtmlWebpackPlugin(&#123;</span><br><span class="line">                   title:&#x27;TS测试&#x27;</span><br><span class="line">               &#125;),</span><br><span class="line">           ]</span><br><span class="line">       </span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<ol start="4">
<li><p>根目录下创建tsconfig.json，配置可以根据自己需要</p>
<ul>
<li><pre><code class="json">&#123;
    &quot;compilerOptions&quot;: &#123;
        &quot;target&quot;: &quot;ES2015&quot;,
        &quot;module&quot;: &quot;ES2015&quot;,
        &quot;strict&quot;: true
    &#125;
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">5. 修改package.json添加如下配置</span><br><span class="line"></span><br><span class="line">   - ```json</span><br><span class="line">     &#123;</span><br><span class="line">       ...略...</span><br><span class="line">       &quot;scripts&quot;: &#123;</span><br><span class="line">         &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,</span><br><span class="line">         &quot;build&quot;: &quot;webpack&quot;,</span><br><span class="line">         &quot;start&quot;: &quot;webpack serve --open chrome.exe&quot;</span><br><span class="line">       &#125;,</span><br><span class="line">       ...略...</span><br><span class="line">     &#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
<li><p>在src下创建ts文件，并在并命令行执行<code>npm run build</code>对代码进行编译，或者执行<code>npm start</code>来启动开发服务器</p>
</li>
</ol>
</li>
</ul>
<h2 id="5、Babel"><a href="#5、Babel" class="headerlink" title="5、Babel"></a>5、Babel</h2><ul>
<li><p>经过一系列的配置，使得TS和webpack已经结合到了一起，除了webpack，开发中还经常需要结合babel来对代码进行转换以使其可以兼容到更多的浏览器，在上述步骤的基础上，通过以下步骤再将babel引入到项目中。</p>
<ol>
<li><p>安装依赖包：</p>
<ul>
<li><code>npm i -D @babel/core @babel/preset-env babel-loader core-js</code></li>
<li>共安装了4个包，分别是：<ul>
<li>@babel&#x2F;core<ul>
<li>babel的核心工具</li>
</ul>
</li>
<li>@babel&#x2F;preset-env<ul>
<li>babel的预定义环境</li>
</ul>
</li>
<li>@babel-loader<ul>
<li>babel在webpack中的加载器</li>
</ul>
</li>
<li>core-js<ul>
<li>core-js用来使老版本的浏览器支持新版ES语法</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p>修改webpack.config.js配置文件</p>
<ul>
<li><pre><code class="javascript">...略...
module: &#123;
    rules: [
        &#123;
            test: /\.ts$/,
            use: [
                &#123;
                    loader: &quot;babel-loader&quot;,
                    options:&#123;
                        presets: [
                            [
                                &quot;@babel/preset-env&quot;,
                                &#123;
                                    &quot;targets&quot;:&#123;
                                        &quot;chrome&quot;: &quot;58&quot;,
                                        &quot;ie&quot;: &quot;11&quot;
                                    &#125;,
                                    &quot;corejs&quot;:&quot;3&quot;,
                                    &quot;useBuiltIns&quot;: &quot;usage&quot;
                                &#125;
                            ]
                        ]
                    &#125;
                &#125;,
                &#123;
                    loader: &quot;ts-loader&quot;,

                &#125;
            ],
            exclude: /node_modules/
        &#125;
    ]
&#125;
...略...
</code></pre>
</li>
<li><p>如此一来，使用ts编译后的文件将会再次被babel处理，使得代码可以在大部分浏览器中直接使用，可以在配置选项的targets中指定要兼容的浏览器版本。</p>
</li>
</ul>
</li>
</ol>
</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://jushden.gitee.io">Jushden</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://jushden.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/">https://jushden.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://jushden.gitee.io" target="_blank">Jushden的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/zhuxiaodong.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%BA%8C%E7%AB%A0%EF%BC%9A%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" title="TS面向对象"><img class="cover" src="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="onerror=null;src='/zhuxiaodong.gitee.io/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">TS面向对象</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/zhuxiaodong.gitee.io/img/duola.jpeg" onerror="this.onerror=null;this.src='/zhuxiaodong.gitee.io/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Jushden</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/zhuxiaodong.gitee.io/archives/"><div class="headline">文章</div><div class="length-num">12</div></a><a href="/zhuxiaodong.gitee.io/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/zhuxiaodong.gitee.io/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/Jushden"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/Jushden" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1416201335@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到朱晓东的博客网站</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC%E4%B8%80%E7%AB%A0-%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-number">1.</span> <span class="toc-text">第一章 快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#0%E3%80%81TypeScript%E7%AE%80%E4%BB%8B"><span class="toc-number">1.1.</span> <span class="toc-text">0、TypeScript简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81TypeScript-%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">1.2.</span> <span class="toc-text">1、TypeScript 开发环境搭建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%9F%BA%E6%9C%AC%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.3.</span> <span class="toc-text">2、基本类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81Babel"><span class="toc-number">1.4.</span> <span class="toc-text">5、Babel</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/zhuxiaodong.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/" title="TS入门"><img src="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="this.onerror=null;this.src='/zhuxiaodong.gitee.io/img/404.jpg'" alt="TS入门"/></a><div class="content"><a class="title" href="/zhuxiaodong.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/" title="TS入门">TS入门</a><time datetime="2023-07-29T09:15:15.878Z" title="发表于 2023-07-29 17:15:15">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/zhuxiaodong.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%BA%8C%E7%AB%A0%EF%BC%9A%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" title="TS面向对象"><img src="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="this.onerror=null;this.src='/zhuxiaodong.gitee.io/img/404.jpg'" alt="TS面向对象"/></a><div class="content"><a class="title" href="/zhuxiaodong.gitee.io/2023/07/29/TypeScript%E7%AC%AC%E4%BA%8C%E7%AB%A0%EF%BC%9A%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" title="TS面向对象">TS面向对象</a><time datetime="2023-07-29T09:15:15.876Z" title="发表于 2023-07-29 17:15:15">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/zhuxiaodong.gitee.io/2023/07/29/React%E5%85%A8%E5%AE%B6%E6%A1%B6/" title="React全家桶"><img src="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="this.onerror=null;this.src='/zhuxiaodong.gitee.io/img/404.jpg'" alt="React全家桶"/></a><div class="content"><a class="title" href="/zhuxiaodong.gitee.io/2023/07/29/React%E5%85%A8%E5%AE%B6%E6%A1%B6/" title="React全家桶">React全家桶</a><time datetime="2023-07-29T09:15:15.875Z" title="发表于 2023-07-29 17:15:15">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/zhuxiaodong.gitee.io/2023/07/29/React%E6%89%A9%E5%B1%95/" title="React扩展"><img src="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="this.onerror=null;this.src='/zhuxiaodong.gitee.io/img/404.jpg'" alt="React扩展"/></a><div class="content"><a class="title" href="/zhuxiaodong.gitee.io/2023/07/29/React%E6%89%A9%E5%B1%95/" title="React扩展">React扩展</a><time datetime="2023-07-29T09:15:15.873Z" title="发表于 2023-07-29 17:15:15">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/zhuxiaodong.gitee.io/2023/07/29/ReactRouter6%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B/" title="React Router 6 快速上手"><img src="https://img1.baidu.com/it/u=3255567619,1492410640&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" onerror="this.onerror=null;this.src='/zhuxiaodong.gitee.io/img/404.jpg'" alt="React Router 6 快速上手"/></a><div class="content"><a class="title" href="/zhuxiaodong.gitee.io/2023/07/29/ReactRouter6%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B/" title="React Router 6 快速上手">React Router 6 快速上手</a><time datetime="2023-07-29T09:15:15.871Z" title="发表于 2023-07-29 17:15:15">2023-07-29</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Jushden</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/zhuxiaodong.gitee.io/js/utils.js"></script><script src="/zhuxiaodong.gitee.io/js/main.js"></script><script src="/zhuxiaodong.gitee.io/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="3136952023" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true"> </div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/zhuxiaodong.gitee.io/js/search/local-search.js"></script></div></body></html>